<?php
namespace coreLib\db\MysqlClass;
use coreLib\ErrorClass\Error;

/**
 * mysql数据库操作类
 **/
class Mysql{

	public  $mysqlConn;				//操作对象句柄
	private $host;					//数据库地址
	private $username;				//用户名称
	private $password;				//用户密码
	private $dbname;				//数据库名称
	private $prefix;				//表前缀
	private $procedureParams; 		//存储过程参数
	private $mysqlResult;			//数据库返回的结果集
	private $mysqlData;				//执行结果
	public  $sql;					//sql语句
	public  $where;					//条件
	private $field;					//字段
	private $sort;					//排序
	private $in;					//in类型的条件
	private $limit;					//分页
	private $nowActionDbName;       //当前操作的数据库名称
	public  $lastAddId;
	
	protected $comparison = ['eq'=>'=','neq'=>'<>','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE','in'=>'IN','notin'=>'NOT IN']; //where条件替换符
	/*
	 * 构造方法
	 * @params {$setting} 数据库配置信息
	 * @return 没有返回值
	 */
	function __construct($setting){
 
        
		$this->host     	   = $setting['host'];
		$this->username 	   = $setting['username'];
		$this->password 	   = $setting['password'];
		$this->dbname 		   = $setting['dbname'];
		$this->prefix		   = $setting['prefix'];
		$this->nowActionDbName = $setting['dbname'];
		
		//创建mysql数据库连接
		$conn = @new \mysqli($this->host,$this->username,$this->password,$this->dbname);
		if(mysqli_connect_error()){
		   Error::Result("DATABASE_ERROR","Mysql_Error:".mysqli_connect_error());
		}
		
		//设置查询编码
		$conn->query("SET NAMES UTF8");

		//数据库连接对象
		$this->mysqlConn = $conn;


	}

	/*数据库更新操作*/
	function delete($table,$where,$isDelete=false,$isPrefix=true){

		
	

		//物理删除（慎用）
		if($isDelete && $GLOBALS["settings"]["isPhysicallyDelete"]){

			if($isPrefix){
				$this->sql = "delete from ".$this->prefix."_".$table;
			}else{
				$this->sql = "delete from ".$table;
			}

			$whereKey   = " where ";
			foreach($where as $k=>$v){
				$whereKey.= $k."='".$v."' and ";
			}

			$whereKey = rtrim($whereKey," and ");
			$this->sql .= $whereKey;

			//执行SQL
			return $this->execSql();

		//逻辑删除
		}else{

			if($isPrefix){
				$this->sql = "update ".$this->prefix."_".$table;
			}else{
				$this->sql = "update ".$table;
			}


			$whereKey   = " where ";
			foreach($where as $k=>$v){
				$whereKey.= $k."='".$v."' and ";
			}

			$whereKey  = rtrim($whereKey," and ");

			$updateKey = " set is_delete = '1'";

			$this->sql .= $updateKey.$whereKey;

			//执行SQL
			return $this->execSql();

		}

		
	}

	//自减少操作
	function updateReduce($table,$where,$field,$inc,$isPrefix = true){

		if(!isset($inc)){
			$inc = 1;
		}
		
		if($isPrefix){
			$this->sql = "update ".$this->prefix."_".$table;
		}else{
			$this->sql = "update ".$table;
		}

		$whereKey   = " where ";
		foreach($where as $k=>$v){
			$whereKey.= $k."='".$v."' and ";
		}

		$whereKey = rtrim($whereKey," and ");

		$updateKey = " set ".$field."=".$field."-".$inc;

		$this->sql .= $updateKey.$whereKey;

		//执行SQL
		return $this->execSql();
		

	}

	//自增操作
	function updateInc($table,$where,$field,$inc,$isPrefix = true){

		if(!isset($inc)){
			$inc = 1;
		}
		
		if($isPrefix){
			$this->sql = "update ".$this->prefix."_".$table;
		}else{
			$this->sql = "update ".$table;
		}

		$whereKey   = " where ";
		foreach($where as $k=>$v){
			$whereKey.= $k."='".$v."' and ";
		}

		$whereKey = rtrim($whereKey," and ");

		$updateKey = " set ".$field."=".$field."+".$inc;

		$this->sql .= $updateKey.$whereKey;

		//执行SQL
		return $this->execSql();
		

	}


	/*数据库更新操作*/
	function update($table,$where,$data,$isPrefix = true){

		if($isPrefix){
			$this->sql = "update ".$this->prefix."_".$table;
		}else{
			$this->sql = "update ".$table;
		}
		

		$whereKey   = " where ";
		foreach($where as $k=>$v){
			$whereKey.= $k."='".$v."' and ";
		}

		$whereKey = rtrim($whereKey," and ");

		$updateKey   = " set ";
		foreach($data as $k=>$v){
			$updateKey.= $k."='".$v."',";
		}

		$updateKey = rtrim($updateKey,",");

		$this->sql .= $updateKey.$whereKey;

		//执行SQL
		return $this->execSql();
	}

	/*数据库写入操作*/
	function insert($table,$data,$isPrefix=true){

		if($isPrefix){
			$this->sql = "insert into ".$this->prefix."_".$table;
		}else{
			$this->sql = "insert into ".$table;
		}

		//创建写入SQL语句的字段项
		$insertKey   = "(";
		$insertValue = "(";
		foreach($data as $k=>$v){
			$insertKey   = $insertKey."".$k.",";
			$insertValue = $insertValue."'".$v."',";
		}

		$insertKey = rtrim($insertKey,",").")";
		$insertValue = rtrim($insertValue,",").")";

		$this->sql = $this->sql.$insertKey." values".$insertValue;

		//执行查询
		$this->mysqlResult = $this->mysqlConn->query($this->sql);

		if(!$this->mysqlResult){
			Error::Result("REQUEST_ERROR",mysqli_error($this->mysqlConn));
		}

		$this->lastAddId = mysqli_insert_id($this->mysqlConn); 

		//执行SQL
		return $this->lastAddId;
	}	


	/*
     * 切换数据库操作
     * @params {$dbName} 切换的数据库名称
	 * @return 返回当前操作对象，用于链式操作
	 */
	function useDB($dbName){

		$this->mysqlConn->query("use ".$dbName);

		$this->nowActionDbName = $dbName;

		return $this;
	}

	/*
     * 字段过滤
     * @params {$field} 需要显示的字段数组
	 * @return 返回当前操作对象，用于链式操作
	 */
	function field( $field ){
	    if( is_array( $field ) )
	    {
	        $newField = "";
	        if(count($field)){
	            //组装字段
	            foreach($field as $k=>$v){
	                if(empty($v)){
	                    $newField .= $k.",";
	                }else{
	                    $newField .= $k." as ".$v.",";
	                }
	            }
	            $this->field = rtrim($newField,",");
	        }
	    }
	    else 
	    {
	        $this->field=$field;
	    }
	    
	    return $this;
	}

	/*
	 * 请求参数分析
	 * @params {$params} 请求参数数组
	 * @return 返回当前操作对象，用于链式操作
	 */
	function params($params){

		$whereStr = "";
		$sortStr  = "";
		$limitStr = "";
		$inStr    = "";
		
		if(count($params)){


			foreach($params as $k=>$v){

    			if($k != "sort_order" && $k != "keywords" && $k != "limit" && $k != "skip" && $k != 'in'&& $k!='_string' && $k!= 'or' && $k!= 'between' && $k != 'intersection'){
    				$where_arr=explode("-", $v);
    
    				if(count($where_arr)>1){
    					if(count($where_arr)== 2 ){// 健/健-值
    
    						$whereStr  .= $where_arr[0]." = '".$where_arr[1]."' and ";
    
    					}elseif(count($where_arr)==3 and strtolower($where_arr[1])!='in'){// 健/健-比较-值
                            if(strtolower($where_arr[1])=='like'){
                                $whereStr .=$where_arr[0].' '.$this->comparison[strtolower($where_arr[1])].' "%'.$where_arr[2].'%" and ';
                            }else{
                                $whereStr .=$where_arr[0].' '.$this->comparison[strtolower($where_arr[1])].' "'.$where_arr[2].'" and ';
                            }
    						
                        }elseif(count($where_arr)==5 and strtolower($where_arr[1])!='in'){
                            if(strtolower($where_arr[1])=='like'){
                                $whereStr .=$where_arr[0].' '.$this->comparison[strtolower($where_arr[1])].' "%'.$where_arr[2].'%" and '
                                          .$where_arr[0].' '.$this->comparison[strtolower($where_arr[3])].' "%'.$where_arr[4].'%" and ';
                            }else{
                                $whereStr .=$where_arr[0].' '.$this->comparison[strtolower($where_arr[1])].' "'.$where_arr[2].'" and '
                                          .$where_arr[0].' '.$this->comparison[strtolower($where_arr[3])].' "'.$where_arr[4].'" and ';
                            }
                            
                        }elseif(count($where_arr)>=5 and strtolower($where_arr[1])!='in' and count($where_arr)<10  ){ //
                            $whereStr .=$where_arr[0].' '.$this->comparison[strtolower($where_arr[1])].' "'.$where_arr[2].'-'.$where_arr[3].'-'.$where_arr[4].'" and '
                                          .$where_arr[0].' '.$this->comparison[strtolower($where_arr[5])].' "'.$where_arr[6].'-'.$where_arr[7].'-'.$where_arr[8].'" and '; 
                        }
    				}elseif(count($where_arr)==1){// 健/值
    					$whereStr  .= $k." = '".$v."' and ";
    				}
    			   
				}

				
                if ($k=='_string' ){
                   
                    $whereStr.=$v.' and ';
                }
    			if($k == "keywords"){
    				 $whereArr = explode("-", $v);
    				 $whereStr .=$whereArr[0]." like '%".$whereArr[1]."%'"." and ";
    				 if(count($whereArr)>2){
                         $whereStr .=$whereArr[0]." like '%".$whereArr[1]."%'"." and ".$whereArr[2]." like '%".$whereArr[3]."%'"." and ";
                     }
    			}
    
    			if($k == "sort_order"){
    
    			   //获取左右排序key与值
				   $sortArr = explode("-", $v);
				//    $sortStr .= $sortArr[0]." ".$sortArr[1];
				   if(count($sortArr) == 3){
					$sortStr .= $sortArr[0]." ".$sortArr[2].",".$sortArr[1]." ".$sortArr[2];
				   }else{
					$sortStr .= $sortArr[0]." ".$sortArr[1];
				   }
    			}
    
    			if($k == "in"){
    
    			   //获取左右排序key与值
    			   $inArr = explode("-", $v);
    			   $inStr .= $inArr[0]." in(".$inArr[1].") and ";
    			   
    			   
				}
				
				if($k == "or"){
    
					//获取左右排序key与值
					$inArr = explode("-", $v);
					$orArr = explode(",",$inArr[1]);
					$inStr .= " (".$inArr[0]."=".$orArr[0]." or ".$inArr[0]."=".$orArr[1].")";
				}

				if($k == 'between'){


					$betweenArr = explode("|", $v);

					if(count($betweenArr)<=1){
      
						$betweenArr = explode("-", $v);
					
						if(count($betweenArr) == 3){
							
							$inStr .= "(".$betweenArr[1]." >= ".$betweenArr[0]." and ".$betweenArr[1]." <= ".$betweenArr[2].")";
	
						}else{
                            
                            $inStr .= "(";
	
							if(is_numeric($betweenArr[0])){
	
								$inStr .= $betweenArr[1]." >= ".$betweenArr[0];
	
							}
	
	
							if(is_numeric($betweenArr[1])){
	
								$inStr .= $betweenArr[0]." <= ".$betweenArr[1];
	
							}
                            
                            $inStr .= ")";
						}
                        
                        $inStr .= " and ";


					}else{
					 
						for($i=0;$i<count($betweenArr);$i++){

							$betweenArr2 = explode("-", $betweenArr[$i]);
							
							if(count($betweenArr2) == 3){

								$inStr .= "(".$betweenArr2[1]." >= ".$betweenArr2[0]." and ".$betweenArr2[1]." <= ".$betweenArr2[2].") and ";
								
							}else{

								if(is_numeric($betweenArr2[0])){
		
									$inStr .= $betweenArr2[1]." >= ".$betweenArr2[0]." and ";
		
								}
		
		
								if(is_numeric($betweenArr2[1])){
		
									$inStr .= $betweenArr2[0]." <= ".$betweenArr2[1]." and ";
		
								}
							}
							


						}
                
//                        $inStr = rtrim($inStr," and ");

					}
					
					
				}

				//交集查询
				if($k=='intersection'){

					$intersectionArr = explode("|", $v);

					$inStr .= "not (";

					$intersectionArr_l = explode("-", $intersectionArr[0]);
					$intersectionArr_r = explode("-", $intersectionArr[1]);

					$inStr .= "(" .$intersectionArr_l[0]."<".$intersectionArr_l[1].") or ";
					$inStr .= "(" .$intersectionArr_r[0].">".$intersectionArr_r[1].")";

					$inStr .= ") and ";

				}

			}
            
          
            $arrStr = explode(" and ", $inStr);
            if ($arrStr[count($arrStr)-1] == "") {
                $inStr = rtrim($inStr," and ");
            }
            
			// if(isset($params['sort_order'])){
    
			// 	//获取左右排序key与值
			// 	$sortArr = explode("-", $params['sort_order']);
			// 	$sortStr .= $sortArr[0]." ".$sortArr[1];
			 
			//  }

			//  if(isset($params['keywords'])){
			// 	$whereArr = explode("-", $params['keywords']);
			// 	$whereStr .= $whereArr[0]." like '%".$whereArr[1]."%'"." and ";
			// }
				

    		
    		//拼接skip、limit
    		if( isset( $params['skip'] ) || isset( $params['limit'] ) )
    		{
    		    if( isset( $params['skip'] ) && !isset( $params['limit'] ) )
    		    {
    		        Error::Result("DATABASE_ERROR",$GLOBALS['errorMsg']['paramsFormatError']);
    		    }
				$limitStr = $params['skip'] . ',' . $params['limit'];
				
				unset( $params['skip'] );
				unset( $params['limit'] );
    		}
    
    		$whereStr = rtrim($whereStr," and");
		}

		$this->where = $whereStr;
		$this->sort  = $sortStr;
		$this->in    = $inStr;
		$this->limit = trim($limitStr,",");


		

		return $this;
	}

	/*
	 * 条件添加
	 * @params {$params} 条件字符串
	 * @return 返回当前操作对象，用于链式操作
	 */
	function where($where){
        if( $where )
        {
        	 $this->where = $this->parseWhere($where);
        }
        return $this;
	}

	//where参数分析(总方法)
	function parseWhere($where){
		$where_str="";
		if(is_string($where)){ //如果为字符串直接执行
			$where_str = $where;
			return $where_str;
		}else{
			$operate  = isset($where['_logic'])?strtoupper($where['_logic']):'';
            if(in_array($operate,array('AND','OR','XOR'))){
                // 定义逻辑运算规则 例如 OR XOR AND NOT
                $operate    =   ' '.$operate.' ';
                unset($where['_logic']);
            }else{
                // 默认进行 AND 运算
                $operate    =   ' AND ';
            }

            //如果是数组解析
           
			foreach($where as $key=>$var){
				if($key=='_string'){ //支持字符串类型

					 $where_str.= $var.$operate ; //$where['_string']='key in (1,2,3)'
				
				}else{

					if(is_string($var[0])){ //$where['key']=['eq','666'] 


						if(strtoupper($var[0])!='NOTLIKE' and strtoupper($var[0])!='LIKE' and strtoupper($var[0])!='IN' and strtoupper($var[0])!="NOTIN" ){
							
							if(!isset($this->comparison[strtolower($var[0])])){
								$where_str.=$key . '="'.$var.'"'.$operate;
							}else{
								$biao=$this->comparison[strtolower($var[0])];
								$where_str.=$key . $biao.'"'.$var[1].'"'.$operate;
							}
							
						}else{

							if(strtoupper($var[0])=='NOTLIKE'  )
							{
								$where_str.=$key.' '.$this->comparison[strtolower($var[0])].' "'.$var[1].'"'.$operate;
							}
							
							if( strtoupper($var[0])=='LIKE')
							{
								$where_str.=$key.' '.$this->comparison[strtolower($var[0])].' "'.$var[1].'"'.$operate;
							}

							if(strtoupper($var[0])=='IN' ){
								$where_str.=$key.' '.$this->comparison[strtolower($var[0])].'('.$var[1].')'.$operate;
							
							}
							if(strtoupper($var[0])=='NOTIN'){
								$where_str.=$key.' '.$this->comparison[strtolower($var[0])].'('.$var[1].')'.$operate;
							}
							
						}
						
						

					}elseif(is_array($var[0]) and is_array($var[1]) and is_string($var[2])){ //复合类型只支持比较运算
				
							$where_str.='('.$key.$this->comparison[strtolower($var[0][0])].'"'.$var[0][1].'" '.strtoupper($var[2]).' '.$key.$this->comparison[strtolower($var[1][0])].'"'.$var[1][1].'")'.$operate;
				    }
				}

				//截取
			}
			$num=-strlen($operate);
			
			$where_str=substr($where_str,0,$num);

			return $where_str;

		}


	}

	/*
	 * 排序添加
	 * @params {$sort} 排序字符串
	 * @return 返回当前操作对象，用于链式操作 
	 */
	function sort($sort){

		$this->sort = $sort;
		return $this;
	}

	/*
	 * 分页添加
	 * @params {$skip}  从第几条开始显示
	 * @params {$limit} 显示几条
	 * @return 返回当前操作对象，用于链式操作 
	 */
	function limit($skip,$limit){

		if(empty($skip)){
		   $skip = 0;		
		}

		if(empty($limit)){
		   $limit = $GLOBALS['settings']['pageLimit'];
		}

		$this->limit = $skip.",".$limit;
		return $this;
	}

	/*
	 * 执行sql拼接
	 * @params {$table} 表名称
	 * @return 没有返回值
	 */
	protected function sqlSplite($table,$isCount=false){

		//判断是否为查询总条数
		if(!$isCount){

			//拼接字段选择
			if($this->field){

				//判断是否存在表前缀
				if(!empty($this->prefix)){
					$this->sql = "select ".$this->field." from ".$this->prefix."_".$table;
				}else{
					$this->sql = "select ".$this->field." from ".$table;
				}
		
			}else{

				//判断是否存在表前缀
				if(!empty($this->prefix)){
					$this->sql = "select * from ".$this->prefix."_".$table;
				}else{
					$this->sql = "select * from ".$table;
				}
			}

		}else{

			//判断是否存在表前缀
			if(!empty($this->prefix)){
				$this->sql = "select count(*) as num from ".$this->prefix."_".$table;
			}else{
				$this->sql = "select count(*) as num from ".$table;
			}

		}

		//拼接条件
		if($this->where){

			if($this->in){
				$this->sql .= " where ".$this->where." and ".$this->in;
			}else{
				$this->sql .= " where ".$this->where;
			}
			
		}else if($this->in){

			$this->sql .= " where ".$this->in;

		}

		//拼接排序
		if($this->sort){
			$this->sql .= " order by ".$this->sort;
		}

		//拼接分页
		if($this->limit){
			$this->sql .= " limit ".$this->limit;
		}

	}

	/*
     * 查询方法（多数据返回）
     * @params {$table} 表名称
     * @params {$isView} true表为视图，false为普通数据表
	 * @return 查询后的结果，二维数组
	 */
	function select($table,$isView=false){

		//判断是否为视图查询，并更改表前缀
		if($isView){
			$this->prefix = "v";
		}
	
		//执行SQL拼接
		$this->sqlSplite($table);

//		echo $this->sql; exit();
//

		//执行SQL
		$this->mysqlData = $this->execSql();

		
		
		return $this->mysqlData;
	}

	/*
     * 查询方法（多数据返回）自定义表名，不使用系统提供的表前缀
     * @params {$table} 表名称
	 * @return 查询后的结果，二维数组
	 */
	function selectTable($table){

		$this->prefix = "";

		//执行SQL拼接
		$this->sqlSplite($table);

		//执行SQL
		$this->mysqlData = $this->execSql();

		return $this->mysqlData;

	}


	/*
     * 查询总条数
     * @params {$table} 表名称
	 * @return 总条数数量
	 */
	function count($table, $isView = false){

		//判断是否为视图查询，并更改表前缀
		if($isView){
			$this->prefix = "v";
		}

		//执行SQL拼接
		$this->sqlSplite($table,true);

		//执行SQL
		$this->mysqlData = $this->execSql();

		
		return $this->mysqlData[0]['num'];

	}


	/*
     * 查询总条数
     * @params {$table} 表名称
	 * @return 总条数数量
	 */
	function countTable($table){

		$this->prefix = "";

		//执行SQL拼接
		$this->sqlSplite($table,true);

		//执行SQL
		$this->mysqlData = $this->execSql();

		
		return $this->mysqlData[0]['num'];

	}


	/*
     * 查询方法（单条数据返回）
     * @params {$table} 表名称
     * @params {$isView} true表为视图，false为普通数据表
     * @return 查询后的结果，一维数组
	 */
	function find($table,$isView=false){

		//判断是否为视图查询，并更改表前缀
		if($isView){
			$this->prefix = "v";
		}

		//执行SQL拼接
		$this->sqlSplite($table);


		//执行SQL
		$this->mysqlData = $this->execSql();


		if($this->mysqlData[0] == NULL){
		   $resutData = array();
		}else{
		   $resutData = $this->mysqlData[0];	
		}

		return $resutData;
	}


	/*
     * 查询方法（单条数据返回）自定义表名，不使用系统提供的表前缀
     * @params {$table} 表名称
	 * @return 查询后的结果，二维数组
	 */
	function findTable($table){

		$this->prefix = "";

		//执行SQL拼接
		$this->sqlSplite($table);

		//执行SQL
		$this->mysqlData = $this->execSql();
		
		if($this->mysqlData[0] == NULL){
		   $resutData = array();
		}else{
		   $resutData = $this->mysqlData[0];	
		}

		return $resutData;
		
	}

	/*
	 * sql执行方法
     * @return 返回结果集
	 */
	function query($sql){

		//结果保存数组
		$dataArr = array();

		//设置查询编码
		$this->mysqlConn->query("SET NAMES UTF8");

		//执行查询
		$this->mysqlResult = $this->mysqlConn->query($sql);

		if(!$this->mysqlResult){
			Error::Result("REQUEST_ERROR",mysqli_error($this->mysqlConn));
		}

		$dataArr = mysqli_fetch_all($this->mysqlResult,MYSQLI_ASSOC);

		return $dataArr;

	}


	/*
	 * sql执行方法
     * @return 返回结果集
	 */
	function execSql(){

		

		//结果保存数组
		$dataArr = array();

		//设置查询编码
		$this->mysqlConn->query("SET NAMES UTF8");

		//执行查询
		$this->mysqlResult = $this->mysqlConn->query($this->sql);

		if(!$this->mysqlResult){
			Error::Result("REQUEST_ERROR",mysqli_error($this->mysqlConn));
		}
		

		$dataArr = mysqli_fetch_all($this->mysqlResult,MYSQLI_ASSOC);


		return $dataArr;
	}
	
	/*
	 * 构造存储过程所需参数
	 * @params {$params} 存储过程参数数组
	 * @params {$actionType} 存储过程的处理类型 C-新增 U-更新 R-查询 D-删除
	 * @params {$wheres} 进行U操作时的条件参数
	 * @return 返回最终拼接好的参数
	 */
	function setProceduerParams($params,$actionType,$wheres=NULL){

		//最终参数结果
		$proParams = "";

		//如果是 写入，查询，删除操作
		if($actionType == 'C' || $actionType == 'R' || $actionType == 'D'){

			//拼装存储过程参数
			for($i=0;$i<count($params);$i++){

				$proParams .= "'".$params[$i]."',";
			}

			$proParams = rtrim($proParams,',');

		//如果是 更新操作	
		}else if($actionType == 'U'){

			//判断是否为关联数组，更新操作要求传递关联数组参数
			if(!is_assoc_array($params) && !is_assoc_array($wheres)){
				Error::Result("BUSINESS_ERROR",$GLOBALS['errorMsg']['noProceduerParamsFormatError']);
			}

			//条件参数处理
			$wheresKeyArr = array();
			$wheresValArr = array();
			foreach($wheres as $k=>$v){

				if(!empty($v)){
					array_push($wheresKeyArr,$k);
					array_push($wheresValArr,$v);
				}
			}

			if(count($wheresKeyArr) != count($wheresValArr)){
				Error::Result("BUSINESS_ERROR",$GLOBALS['errorMsg']['noProceduerParamsCountError']);
			}

			//更新参数处理
			$paramsKeyArr = array();
			$paramsValArr = array();
			foreach($params as $k=>$v){

				if((!empty($v)) || $v == '0'){
					array_push($paramsKeyArr,$k);
					array_push($paramsValArr,$v);
				}

			}



			if(count($paramsKeyArr) != count($paramsValArr)){
				Error::Result("BUSINESS_ERROR",$GLOBALS['errorMsg']['noProceduerParamsCountError']);
			}

			//拼接最终参数结果
			$proParams = "'".implode(",",$wheresKeyArr)."','".implode(",",$wheresValArr)."','".implode(",",$paramsKeyArr)."','".implode(",",$paramsValArr)."'";


		}else {
			Error::Result("BUSINESS_ERROR",$GLOBALS['errorMsg']['noProceduerActionTypeParamsError']);
		}

		
		$this->proParams = $proParams;
		return $proParams;
	}
	
	/**
	 * 生成单条存储过程语句
	 * @param unknown $proName
	 * @param number $type
	 * @param string $count
	 */
	public function createProcedureSql($proName,$type=1)
	{
	    if($type==1){
	        $str='';
	
	    }else if($type==2){
	        $str=',@outId';
	    }else if( $type == 3 )
	    {
	        $str=',@inId';
	    }
	     
	    return "CALL {$this->nowActionDbName}.{$proName}({$this->proParams},@code,@msg{$str})";
	     
	}

    
	/**
	 * 拼接多存储过程语句
	 * @param unknown $array
	 * @return string
	 */
	public function jointProcedureSqls( $array )
	{
	    $str='start transaction;set @panding=1;';
	    $num=count($array)-1;
	    foreach( $array as $key => $val )
	    {   
	       if($key==$num)
           {
               $str .= $val."CALL EC_FUNCTION_PROCEDURE_CTRL(@code, '1');";
           }else{
               $str .= $val."CALL EC_FUNCTION_PROCEDURE_CTRL(@code, '0');";
           }   
	    }
	    
	    return $str;
	}
	
	/**
	 * 批量执行存储过程 
	 * @param unknown $sql
	 * @return number
	 */
	public function batchExecProcedure($sql)
	{
	    $res = $this->mysqlConn->multi_query($sql);
	    
	    $arr=[];
	    if ($res) {
	        do {
	            if ($result = $this->mysqlConn->store_result()) {
	                while ($row = $result->fetch_array()) {
	                    $arr[]= $row[0];
	                }
	               $result->free();
	            }
	             
	        } while (@$this->mysqlConn->next_result());
	    }
	    
// 	    var_dump($arr);
	    $result = $arr[count($arr)-1];
	    if( $result == -90 )
	    {
	       return true;   
	    }
	    else
	    {
	        return false;
	    }
	}
	
	/*
	 * 执行存储过程
	 * @params {$proName} 存储过程名称
	 * @params {$params} 存储过程参数
	 * @params {$resultType} 返回的类型是带数据的类型还是不带数据的类型 ACTION - 不带数据 
	 * @return 返回最终拼接好的参数
	 */
	function execProceduer($proName,$params,$resultType="ACTION"){

		//结果保存数组
		$dataArr = array();

		//调用存储过程
		$proceStr = "CALL {$this->nowActionDbName}.{$proName}({$this->proParams},@code,@msg)";
		
		//获取存储过程结果
		$this->mysqlResult = $this->mysqlConn->query($proceStr,MYSQLI_STORE_RESULT);

		//查看存储过程是否调用成功
		if(!$this->mysqlResult){
			Error::Result("BUSINESS_ERROR",$GLOBALS['errorMsg']['noProceduerError']);
		}

		//获取存储过程返回CODE与MESSAGE
		$proCodeResult	= $this->mysqlConn->query("select @code");
		$proMsgResult   = $this->mysqlConn->query("select @msg");

		//获取CODE与MESSAGE信息
		$proCode = @mysqli_fetch_all($proCodeResult,MYSQLI_ASSOC)[0]['@code'];
		$proMsg  = @mysqli_fetch_all($proMsgResult, MYSQLI_ASSOC)[0]['@msg'];


		//判断存储过程返回类型
		if($resultType == "ACTION"){

			if($proCode < 0){
				Error::Result("BUSINESS_ERROR",$proMsg);	
			}

			return true;

		}else{
		
			//如果是数据返回类型，则获取返回数据信息
			@$proResult = mysqli_fetch_all($this->mysqlResult,MYSQLI_ASSOC)[0];

			if(!$proResult){
				Error::Result("BUSINESS_ERROR",$proMsg);
			}

			return $proResult;
		}

	}


	


	/*
	 * 释放存储过程占用的资源
	 * @return 没有返回值
	 */
	function clearStoredResults(){
	    while($this->mysqlConn->more_results() && $this->mysqlConn->next_result()){
	      if($l_result = $this->mysqlConn->store_result()){
	         $l_result->free();
	      }
	    }
	}

	/*
	 * 析构方法
	 * @return 没有返回值
	 */
	function __destruct(){

		//释放结果内存
		if($this->mysqlResult!=NULL){
			@mysqli_free_result($this->mysqlResult);
		}
		

		//关闭之前建立的mysql数据库连接
		if($this->mysqlConn!=NULL){
			@mysqli_close($this->mysqlConn);
		}
		

	}
	

}
